<template>
	<a-select
		v-model:value="typeId"
		style="width: 100%"
		allow-clear
		placeholder="选择饲料种类"
		:options="options"
		@change="handleChange"
	></a-select>
</template>

<script setup="feedTypeSelect">
	import bizFeedTypeApi from "@/api/biz/bizFeedTypeApi";

	const props = defineProps({
		category : String,
		required : false,
	});
	const typeId = ref();
	const options = ref([]);
	const emit = defineEmits(['update:typeId']);
	const listData = ref([]);

	// 监听父组件传入的 category 属性，当其发生变化时执行获取列表的操作
	watch(() => props.category, (newVal, oldVal) => {
		if (newVal) {
			getTypeList(newVal);
		}
	});

	const getTypeList = (category) => {
		const data = {
			category : category,
		}
		bizFeedTypeApi.getFeedTypeByCategory(data)
			.then(resp =>{
				listData.value = resp;
				mapDataToOptions();
			})
			.catch(resp =>{
				console.log("catch:",resp);
			});
	}

	const mapDataToOptions = () => {
		options.value = listData.value.map(item => ({
			value: item.id,
			label: item.name,
		}));
	};

	const handleChange = (value)=> {
		if(value === undefined){
			emit('update:typeId', undefined);
		}
	  	emit('update:typeId', value);
	}

	const clearTypeId = () => {
		typeId.value = undefined;
		emit('update:typeId', undefined);
	}

	defineExpose({
		clearTypeId
	});
</script>

<style scoped>

</style>
